package com.lvtn.adsonandroid;

import java.io.File;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;


import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
//import android.content.Intent;
import android.text.TextUtils;
//import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
//import android.widget.TextView;
//import android.widget.TextView;
import android.widget.Toast;

public class EditUserDetailActivity extends Activity {
	private EditText name;
	private EditText email;
	//private Bundle backup;
	private EditText phone;
	private EditText address;
	private ImageView avar;
	private Button change;
	private String mName;
	private String mEmail;
	private String mPhone;
	private String newMail;
	private String mAddress;
	private static final int SELECT_FILE1 = 1;
    private String selectedImagePath;
	String path;
	private EditUserDetail mAuthTask = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_user_detail);
	//	backup = savedInstanceState;
		Bundle extras = this.getIntent().getExtras();
		name = (EditText) findViewById(R.id.user_name);
		phone = (EditText) findViewById(R.id.user_phone);
		//email = (EditText) findViewById(R.id.email);
		address = (EditText) findViewById(R.id.user_address);
		avar = (ImageView) findViewById(R.id.imgavat);
		change = (Button) findViewById(R.id.butchange);
		Intent intent=getIntent();
		 //có intent rồi thì lấy Bundle dựa vào Package
		//Bundle pack= intent.getBundleExtra("info"); 
		name.setText(extras.getString("NAME"));
	    mEmail =extras.getString("EMAIL");
	    //email.setText(mEmail);
		phone.setText(extras.getString("PHONE"));
		address.setText(extras.getString("ADDRESS"));
		path =extras.getString("AVARTA");
		new DownloadImageTask(avar).execute(path);
		//---change avarta-------------------
		change.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				openGallery(SELECT_FILE1);
			}
		});
		/*-------------save info ------------------------*/
		findViewById(R.id.save_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptEdit();
						
					}
				});
		
	}
	//-----------------------------------------------------------------------------
	private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
		  ImageView bmImage;

		  public DownloadImageTask(ImageView bmImage) {
		      this.bmImage = bmImage;
		  }

		  protected Bitmap doInBackground(String... urls) {
		      String urldisplay = urls[0];
		      Bitmap mIcon11 = null;
		      try {
		        InputStream in = new java.net.URL(urldisplay).openStream();
		        mIcon11 = BitmapFactory.decodeStream(in);
		      } catch (Exception e) {
		          Log.e("Error", e.getMessage());
		          e.printStackTrace();
		      }
		      return mIcon11;
		  }

		  protected void onPostExecute(Bitmap result) {
		      bmImage.setImageBitmap(result);
		  }
		}
	//-------------------------lay anh-------------------//
	 public void openGallery(int req_code){
		 
	        Intent intent = new Intent();
	        intent.setType("image/*");
	        intent.setAction(Intent.ACTION_GET_CONTENT);
	        startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
	   }
	 
	   public void onActivityResult(int requestCode, int resultCode, Intent data) {
	 
	        if (resultCode == RESULT_OK) {
	        	if (requestCode == SELECT_FILE1) {
	                Uri selectedImageUri = data.getData();
	                selectedImagePath = getPath(selectedImageUri);
	                System.out.println("Image Path : " + selectedImagePath);
	                avar.setImageBitmap(BitmapFactory.decodeFile(selectedImagePath));
	        }
	        }
	    }
	 
	    public String getPath(Uri uri) {
	        String[] projection = { MediaStore.Images.Media.DATA };
	        Cursor cursor = managedQuery(uri, projection, null, null, null);
	        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	        cursor.moveToFirst();
	        return cursor.getString(column_index);
	    }
	    /////////////////////////////////////////
	public void attemptEdit() {
		if (mAuthTask != null) {
			return;
		}

		// Reset errors.
		name.setError(null);
		phone.setError(null);
		address.setError(null);

		// Store values at the time of the login attempt.
		mName = name.getText().toString();
		mPhone = phone.getText().toString();
		mAddress = address.getText().toString();
		//newMail = email.getText().toString();

		boolean cancel = false;
		View focusView = null;

		if (TextUtils.isEmpty(mName)) {
			name.setError(getString(R.string.error_field_required));
			focusView = name;
			cancel = true;
		} 
		if (TextUtils.isEmpty(mPhone)) {
			phone.setError(getString(R.string.error_field_required));
			focusView = phone;
			cancel = true;
		} 
		if (TextUtils.isEmpty(mAddress)) {
			address.setError(getString(R.string.error_field_required));
			focusView = address;
			cancel = true;
		} 
		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			//mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
			//showProgress(true);
			Log.d("test","van on 1");
			mAuthTask = new EditUserDetail();
			mAuthTask.execute((Void) null);
		}
	}
	public class EditUserDetail extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			 String urlString = "http://10.0.2.2/android/";
		       File file = new File(selectedImagePath);
		       FileBody file1 = new FileBody(file);
		        try
		        {
		             HttpClient client = new DefaultHttpClient();
		             HttpPost post = new HttpPost(urlString);
		             MultipartEntity reqEntity = new MultipartEntity();
		             reqEntity.addPart("image_avarta", file1);
		             reqEntity.addPart("avarta", new StringBody("1"));	
		             reqEntity.addPart("tag", new StringBody("update"));	
		             reqEntity.addPart("name", new StringBody(mName));
		             reqEntity.addPart("phone", new StringBody(mPhone));
		             reqEntity.addPart("address", new StringBody(mAddress));
		             reqEntity.addPart("oldmail", new StringBody(mEmail));
		             //reqEntity.addPart("newmail", new StringBody(newMail));
		             
		             post.setEntity(reqEntity);
		             HttpResponse response = client.execute(post);
		             HttpEntity resEntity;
		             resEntity = response.getEntity();
		             final String response_str = EntityUtils.toString(resEntity);
		             if (resEntity != null) {
		                 Log.i("RESPONSE",response_str);
		                 runOnUiThread(new Runnable(){
		                        public void run() {
		                             try {
		                               // res.setTextColor(Color.GREEN);
		                               //res.setText("n Response from server : n " + response_str);
		                                Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
		                                finish();
		                            } catch (Exception e) {
		                                e.printStackTrace();
		                            }
		                           }
		                    });
		             }
		            // i=0;
		        }
		        catch (Exception ex){
		             Log.e("Debug", "error: " + ex.getMessage(), ex);
		        }
		        return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			//mAuthTask = null;
			if (success) {
				Log.d("test","van on 4");
				finish();
				//onCreate(backup);
			 //  Intent detail=new Intent(getApplicationContext(),AccessPrivateInforActivity.class);
				//String message="logined";
			//	main.putExtra(EXTRA_MESSAGE, mEmail);
			//	detail.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			//	startActivity(detail);							
			//	finish();
            }
			
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;
		//	showProgress(false);
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.edit_user_detail, menu);
		return true;
	}

}
